
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import AQueryTable from '@dangojs/a-query-table';
import { PRECESS_COLUMNS } from '@/constants/indexDevelop';
import { IconCaretDown, IconLeft } from '@arco-design/web-vue/es/icon';
import ModalDialog from '@/components/ModalDialog/index.vue';
import { Message, Modal } from '@arco-design/web-vue';
import ChangeRecord from '@/arco-components/lineTime/index.vue';
import API from '@/services';
import { concat } from 'lodash';
import * as RouteNames from '@/router/consts';
import { useRouter } from 'vue-router';
const router = useRouter();
const props = defineProps({
  indexPrecessObj: {
    type: Object
  }
});

const showMoreList = ref<boolean>(false);

const loginRef = ref();
const indexProcessData: any = reactive({
  total: 0,
  data: [] as any[]
});

const metricsRef = ref<any>(null);

const modalVisible = ref(false);
// 指标加工-加工逻辑table数据
const metricsLoginData = async () => {
  try {
    const { code, data } =
      await API.metricsModelRelation.getGetMetricsModelListById({
        id: props.indexPrecessObj?.id
      });
    if (code === 200) {
      indexProcessData.data = data || [];
    }
  } catch (error) {}
};
const loginFrom = reactive({
  remark: ''
});
const precessLogin = reactive<any>({
  data: {}
});
// 上线和下线
const offOnLine = async (params: any) => {
  return new Promise(async (resolve, reject) => {
    try {
      const { code, data } = await API.metricsModelRelation.postOffLine({
        ...params
      });
      if (code === 200) {
        metricsLoginData();
        resolve(data);
      }
    } catch (error) {
      reject(error);
    }
  });
};
const handleOk = async () => {
  const err = await loginRef.value.validate();
  if (!err) {
    const { id, logicName } = precessLogin.data;
    const params = {
      id,
      logicName,
      status: 1, // 上线状态，
      remark: loginFrom.remark
    };
    await offOnLine(params);
    modalVisible.value = false;
    loginFrom.remark = '';
    Message.success('上线成功');
  }
};
// 下线
const onOffline = async (record: any) => {
  const { id } = record;
  const params = {
    id,
    status: 2 // 下线状态，
  };
  await offOnLine(params);
  Message.success('下线成功');
};
const onDelete = (record: any, b: boolean) => {
  if (b) return;
  Modal.confirm({
    modalClass: 'model-message-confirm',
    title: '提示',
    content: '指标逻辑删除后，将无法在取数、看板等场景使用，请确认是否删除？',
    simple: false,
    closable: true,
    okText: '确认删除',
    okButtonProps: {
      style: {
        backgroundColor: '#FF1A3B'
      }
    },
    onBeforeOk: (done) => {
      handleDeleteMetrics(record.id)
        .then(() => {
          Message.success('删除成功');
          metricsLoginData();
        })
        .finally(() => {
          done(true);
        });
    }
  });
};
// 删除指标加工逻辑
const handleDeleteMetrics = async (id: any) => {
  try {
    await API.metricsModelRelation.deleteDelMetricsModelById({ id });
    // todo: API接口出错不会出现异常
    return true;
  } catch (error) {
    throw error;
  }
};
const recordParams = reactive({
  pageSize: 10,
  pageNum: 1
});
const recordList = reactive<any>({
  data: [],
  bottom: false,
  total: 1,
  noDataTips: '已经到底了~',
  loadMoreText: '点击加载更多',
  emptyText: '您还没有变更记录哟~'
});

// 变更记录列表
const metricsRecordId = ref();
const getMetricsModelLog = async () => {
  recordList.data = [];
  try {
    const { code, data, msg } =
      await API.metricsModelRelation.postGetMetricsModelLog({
        metricsModelId: metricsRecordId.value,
        ...recordParams
      });
    if (code === 200) {
      if (data?.list && data.list.length < 10) {
        recordList.bottom = true;
      }
      recordList.data = concat(recordList.data, data?.list || []);
      recordList.total = Number(data?.total);
    } else {
      Message.error(msg || '接口出错了');
    }
  } catch (error) {}
};
const handleNextList = () => {
  recordParams.pageNum += 1;
  getMetricsModelLog();
};

// 新建加工逻辑以及编辑指标加工进入指标加工工作台
const handleBuildIndex = (v?: any) => {
  if (
    !v &&
    props.indexPrecessObj?.metricsType == 2 &&
    indexProcessData.data.length > 0
  ) {
    Message.warning('派生指标只能创建一个加工逻辑');
    return false;
  }
  if (
    !v &&
    props.indexPrecessObj?.metricsType == 3 &&
    indexProcessData.data.length > 0
  ) {
    Message.warning('衍生指标只能创建一个加工逻辑');
    return false;
  }
  let query: any = {};
  if (v) {
    query = {
      status: v.status,
      id: v.id
    };
  }
  query.metricsId = props.indexPrecessObj?.id;
  //判断指标类型
  query.metricsType = props.indexPrecessObj?.metricsType;
  //判断页面文字大小，防止刷新
  query.fontSize = document.getElementsByTagName('html')[0].style.fontSize;
  router.push({
    name: RouteNames.ROUTER_INDICATORTABLE,
    query: {
      ...query
    }
  });
};
onMounted(() => {
  metricsLoginData();
});
const visible = ref(false);
</script>
<template>
  <div class="dis-flex space-between align-item fs14 fw">
    <span>加工逻辑</span>
    <a-button type="primary" @click="handleBuildIndex()">新建加工逻辑</a-button>
  </div>
  <div class="tabs-table_header mt-10">
    <AQueryTable
      size="small"
      ref="metricsRef"
      :columns="PRECESS_COLUMNS"
      :data="indexProcessData.data"
      :bordered="false"
      :pagination="false"
    >
      <template #logicName="{ record }">
        <span
          class="col_blue cp"
          @click="
            () => {
              handleBuildIndex(record);
            }
          "
          >{{ record.logicName }}</span
        >
      </template>
      <template #status="{ record }">
        <span v-if="record.status === 0">未上线</span>
        <span v-else-if="record.status === 1">上线</span>
        <span v-else-if="record.status === 2">下线</span>
      </template>
      <template #operator="{ record }">
        <div class="oprator dis-flex">
          <span
            v-show="record.status != 1"
            class="col_blue cp"
            @click="
              () => {
                modalVisible = true;
                precessLogin.data = record;
              }
            "
            >上线</span
          >
          <a-popconfirm
            :icon="null"
            content="指标逻辑下线后，将无法在取数、看板等场景使用，请确认是否下线？"
            @ok="onOffline(record)"
            :ok-button-props="{size:'small'}"
            :cancel-button-props="{size:'small'}"
            :content-style="{width:'300px'}"
          >
            <template #icon><span></span></template>
            <span v-show="record.status == 1" class="col_blue cp">下线</span>
          </a-popconfirm>
          <span class="line">|</span>
          <div
            class="oprator-more"
            @mouseout="() => (showMoreList = true)"
            @mouseover="() => (showMoreList = false)"
          >
            <a-dropdown>
              <span class="col_blue cp">
                更多
                <icon-caret-down />
              </span>
              <template #content>
                <a-doption
                  @click="
                    () => {
                      metricsRecordId = record.id;
                      visible = true;
                      getMetricsModelLog();
                    }
                  "
                  >变更记录</a-doption
                >
                <a-doption
                  :disabled="record.status === 1"
                  @click="onDelete(record, record.status === 1)"
                  >删除</a-doption
                >
              </template>
            </a-dropdown>
          </div>
        </div>
      </template>
    </AQueryTable>
  </div>
  <a-drawer
    :visible="visible"
    :esc-to-close="false"
    :mask-closable="false"
    width="552px"
    @ok="
      () => {
        visible = false;
        recordParams.pageNum = 1;
      }
    "
    @cancel="
      () => {
        visible = false;
        recordParams.pageNum = 1;
      }
    "
    unmountOnClose
  >
    <template #title>
      <span
        class="col_333 cp fw"
        @click="
          () => {
            visible = false;
          }
        "
      >
        <icon-left />
        返回
      </span>
      <span class="col_333 fw ml-10">变更记录</span>
    </template>
    <div>
      <change-record :record-list="recordList" @fetchData="handleNextList">
        <template v-slot:content="{ item }">
          <div class="line-time">
            <span class="fw line-time-l"> {{ item.createByName }}</span>
            <span class="line-time-r">{{ item.operateType }}</span>
          </div>
        </template>
      </change-record>
    </div>
  </a-drawer>
  <modal-dialog
    class="inlie-login-dialog"
    :modal-visible="modalVisible"
    modalTitle="上线加工逻辑"
    titleAlign="start"
    @update:modalVisible="(v) => (modalVisible = v)"
    @cancelModal="() => (loginFrom.remark = '')"
    @sureModal="handleOk"
  >
    <template v-slot:body>
      <a-form ref="loginRef" :model="loginFrom" :style="{ width: '100%' }">
        <a-form-item field="name" label="ID：">
          {{ precessLogin.data.id }}
        </a-form-item>
        <a-form-item field="post" label="名称：">
          {{ precessLogin.data.logicName }}
        </a-form-item>
        <a-form-item
          field="remark"
          label="描述："
          :rules="[{ required: true, message: '描述信息是必传项' }]"
        >
          <a-textarea v-model="loginFrom.remark"> </a-textarea>
        </a-form-item>
      </a-form>
    </template>
  </modal-dialog>
</template>

<style lang="scss">
.inlie-login-dialog .arco-modal-body {
  padding: 18px 18px 0 12px;
  .arco-form-item {
    margin-bottom: 12px;
    &:last-child {
      margin-bottom: 18px;
    }
    &:first-child {
      margin-bottom: 6px;
    }
    .arco-col-5 {
      flex: 0 0 15%;
      width: 15%;
    }
    .arco-col-19 {
      flex: 0 0 85%;
      width: 85%;
    }
  }
}

@import './index.scss';
</style>
